package cn.maxmc.murderaddons.machine.machines

import cn.maxmc.murderaddons.MurderAddons
import cn.maxmc.murderaddons.machine.BaseMachine
import cn.maxmc.murderaddons.machine.MachineType
import cn.maxmc.murderaddons.task.TaskType
import io.izzel.taboolib.internal.xseries.messages.ActionBar
import io.izzel.taboolib.module.locale.TLocale
import org.bukkit.Bukkit
import org.bukkit.Location
import org.bukkit.configuration.serialization.SerializableAs
import org.bukkit.entity.Player
import org.bukkit.scheduler.BukkitTask
import java.util.concurrent.atomic.AtomicInteger

@SerializableAs("ScannerMachine")
class ScannerMachine: BaseMachine {
    constructor(mainLocation: Location): super(MachineType.SINGLE_LOCATION, TaskType.COMMON, mainLocation)
    constructor(map: Map<String,Any>): super(map)

    override fun requestTask(player: Player, loc: Location) {
        cache.add(player)
        TLocale.sendTo(player,"task.scanner.start")
        val process = AtomicInteger(0)
        var task: BukkitTask? = null
        task = Bukkit.getScheduler().runTaskTimer(MurderAddons.plugin, Runnable {
            if (player.location.distance(mainLocation) > 5) {
                TLocale.sendTo(player,"task.scanner.cancel")
                Bukkit.getScheduler().scheduleSyncDelayedTask(MurderAddons.plugin) { task!!.cancel() }
            }
            val current = process.addAndGet(1)
            showProcess(player,current)
            if(current >= 10) {
                finish(player)
                TLocale.sendTo(player,"task.scanner.finish")
                Bukkit.getScheduler().scheduleSyncDelayedTask(MurderAddons.plugin) { task!!.cancel() }
            }
        }, 0L, 20L)
    }

    private fun showProcess(player: Player, process: Int) {
        val stringBuffer = StringBuffer("§b■■■■■■■■■■")
        stringBuffer.insert(process+2,"§7")
        ActionBar.sendActionBar(player,TLocale.asString("task.scanner.process",stringBuffer.toString()))
    }

}